<template>
  <div class="temporary">
    <el-form label-position="top" :model="form"  ref="form" :rules="rules" class="newbusiness-form tempor-newbusiness-form">
      <div class="timedown" v-if="busTimeObj.totalExpireTime && busTimeObj.totalExpireTime !== 0.1">
            <span>
              <el-popover
                ref="popover4"
                placement="bottom-start"
                trigger="hover"
                :content="$t(busTimeObj.totalTimeState)">
              </el-popover>
              <i class="iconfont icon-zongshichang time"></i>
              <el-button type="text" v-popover:popover4 v-bind:style="{ color: totalTimeColor}">{{totalExpireTimeDisplay}}</el-button>
            </span>
      </div>
      <p class="title">{{$t('business.stagingBusiness')}}</p>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item :label="$t('business.businessFlow')" class="business-type">
            <el-select size="mini" v-model="form.flow" filterable placeholder="" @change="businessTypeChange" :disabled="disabled" class="width-full">
              <el-option  v-for="item in businessTypeArr"
                          :label="item.label"
                          :key="item.value"
                          :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('business.priorityLabel')">
            <el-radio-group v-model.trim="form.priority">
              <el-radio size="mini" :label="'1'" :disabled="disabled">{{this.$t('business.priority1')}}</el-radio>
              <el-radio size="mini" :label="'2'" class="business-priority2" :disabled="disabled">{{this.$t('business.priority2')}}</el-radio>
              <el-radio size="mini" :label="'3'" class="business-priority3" :disabled="disabled">{{this.$t('business.priority3')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <base-form :items="items"
                 ref="stepFields"
                 :disabled="disabled"
                 @showBigImg="showBigImg">
      </base-form>
      <el-row :gutter="20" v-if="operatePane" class="padding-b">
        <el-col :span="24">
          <el-form-item :label="$t('business.nextStep')">
            <el-select size="mini" v-model="form.nextAction" filterable placeholder="" @change="nextStepChange" class="width-full">
              <el-option  v-for="item in nextAction"
                          :label="item.label"
                          :key="item.value"
                          :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('business.handlePeople')" prop="nextUser">
            <el-select size="mini" v-model="form.nextUser" filterable placeholder="" filterable class="width-full">
              <el-option  v-for="item in dealAgent"
                          :label="item.label"
                          :key="item.value"
                          :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="line"></div>
      <el-row>
        <el-col :span="24">
          <span class="follow-label fl">{{$t('business.followedAgentsSetting')}}</span>
          <div class="follow-agent-wrap">
            <span class="follow-agent follow-common" v-for="item in folllowedAgents" :key="item._id">{{item.label}}<i class="el-icon-close" @click.stop="closeFollowedAgents(item._id)" v-show="!disabled"></i></span>
            <el-popover
              ref="popover4"
              placement="bottom"
              @show="popoverShow"
              width="240"
              trigger="click">
              <agent-tree :readSeat="folllowedAgents" ref="agentTree" @saveFollowedAgents="saveFollowedAgents"></agent-tree>
            </el-popover>
            <span class="follow-agent-add follow-common"  v-popover:popover4 v-show="!disabled"><i class="el-icon-plus"></i> {{$t('public.add')}}</span>
          </div>
        </el-col>
         <el-col :span="24">
          <related-bussiness :relatedBusiness="form.relatedBusiness" :relatedBusinessShow="true" @saveRelatedBusiness="saveRelatedBusiness" @closeRelatedBusiness="closeRelatedBusiness"></related-bussiness>
        </el-col>
        <!-- 关联会话 -->
        <el-col :span="24">
          <related-session :relatedWebchats="form.relatedWebchats" :relatedSessionShow="true" @saveRelatedSession="saveRelatedSession" @closeRelatedSession="closeRelatedSession"></related-session>
        </el-col>
        <!-- 关联通话 -->
        <el-col :span="24">
          <related-call :relatedCallSheet="form.relatedCallSheet" :relatedCallShow="true" @saveRelatedCall="saveRelatedCall" @closeRelatedCall="closeRelatedCall"></related-call>
        </el-col>
        <el-col :span="24">
          <affix :label="'处理工单-' + nextStepName" :bodyStyle="{'padding-bottom': '0px'}" v-if="actionItems.length"></affix>
          <base-form ref="actionFields" v-if="actionItemsChange" :items="actionItems" @showBigImg="showBigImg" :disabled="disabled"></base-form>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="log">
        <el-col :span="24">
          <span class="lastUser fl">{{lastUpdateUser}}</span>
          <span class="fl deal-time">{{$t('business.deal')}}</span>
          <span class="fl">{{detail.lastUpdateTime}}</span>
        </el-col>
      </el-row>
    </el-form>
    <div class="btn-wraper clearBoth" v-if="operatePane">
      <div class="btns">
        <el-button class="primary_btn" @click.stop="submit('temp')" v-if="tempBtn" :disabled="disabledBtn">{{$t('business.staging')}}</el-button>
        <el-button type="primary" class="primary_btn" @click.stop="submit('new')" :disabled="disabledBtn">{{$t('business.submit')}}</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import affix from '../../../../ui-modules/affix/Affix.vue'
  import BaseForm from '../base/BaseForm'
  import AgentTree from '../agentTree.vue'
  import {throttle} from 'lodash'
  import {getCache, deepClone, update} from '@/utils/m7Utils.js'
  import { commitImgType2 } from '@/utils/publicMethod.js'
  import {formRollToFirstError} from '@/utils/validate.js'
  import relatedBussiness from '../relatedBussiness.vue'
  import relatedSession from '../relatedSession.vue'
  import relatedCall from '../relatedCall.vue'
  import {fieldsExtend, busTimeDown, showCountDown, getRoleAgents, getRoleActions, getStepRoles,getStepQueues, getQueueAgents, getFlowAction, getStartStep, hasAccessForFlow, getObjectById} from '@/utils/workflowUtils.js'
  export default {
    name: 'temporaryBus',
    props: {
      detail: Object,
      cacheId: {type: String, default: ''} // 缓存工单信息的id
    },
    data () {
      return {
        loading: true,
        disabled: false,
        operatePane: false,
        tempBtn: true,
        form: {
          _id: this.detail._id,
          flow: '',
          nextAction: '',
          nextUser: '',
          priority: this.detail.priority,
          followedAgents: this.detail.followedAgents || [],
          relatedBusiness:this.detail.relatedBusiness || [],
          relatedWebchats:this.detail.relatedWebchats || [],
          relatedCallSheet:this.detail.relatedCallSheet || [],
        },
        items: [
        ],
        actionItems: [],
        nextAction: [],
        dealAgent: [],
        totalTimeColor: '',
        busTimeObj: {},
        stop: {stop: ''},
        disabledBtn: false,
        firstIn: true,
        businessTypeArr: [],
        rules: {
          nextUser: [
            {required: true, message: this.$t('business.masterRequierd'), trigger: 'change'}
          ]
        },
        nextStepName: '',
        flowTemplate: {},
        stepCacheCurId: '',    //   动作数据 id
        actionItemsChange: true,    //   动作数据 更新
        cid:''
      }
    },
    components: {
      affix,
      BaseForm,
      AgentTree,
      relatedBussiness,
      relatedSession,
      relatedCall
    },
    watch: {
      'detail': function () {
        let current = this.businessTypeArr.filter((item) => {
          return item.value === this.detail.flow
        })
        if (current.length === 0) {
          this.form.flow = ''
          this.items = []
          this.disabled = true
          this.operatePane = false
        } else {
          this.form.flow = this.detail.flow
          this.businessTypeChange(this.detail.flow, true)
        }
      },
      cid(){
        if(this.$store.state.business.current.currentCustomer){
          return this.$store.state.business.current.currentCustomer._id
        }
      }
    },
    methods: {
      //保存关联工单
      saveRelatedBusiness(searchContent){
        if(!this.form.relatedBusiness.includes(searchContent)){
          this.form.relatedBusiness.push(searchContent)
        }else{
          this.$message.error(this.$t('business.businessTip2'))
        }
      },
      //删除关联工单
      closeRelatedBusiness(number){
        let index = this.form.relatedBusiness.indexOf(number)
        this.form.relatedBusiness.splice(index,1)
      },
      //保存关联会话
      saveRelatedSession(searchContent){
         // 不能添加本身
        if(this.cacheId && this.cacheId === searchContent){
          this.$message.error(this.$t('business.businessTip8'))
        } else {
          if(!this.form.relatedWebchats.includes(searchContent)){
            this.form.relatedWebchats.push(searchContent)
          }else{
            this.$message.error(this.$t('business.businessTip3'))
          }
        }
      },
      //删除关联会话
      closeRelatedSession(number){
        let index = this.form.relatedWebchats.indexOf(number)
        this.form.relatedWebchats.splice(index,1)
      },
      // 保存关联通话
      saveRelatedCall(searchContent){
        if(!this.form.relatedCallSheet.includes(searchContent)){
          this.form.relatedCallSheet.push(searchContent)
        }else{
          this.$message.error(this.$t('business.businessTip4'))
        }
      },
      // 删除关联通话
      closeRelatedCall(number){
        let index = this.form.relatedCallSheet.indexOf(number)
        this.form.relatedCallSheet.splice(index,1)
      },
      showBigImg (data) {
        // 获取所有包含imgA的图片
        let _array = this.$el.querySelectorAll('.tempor-newbusiness-form .imgA')
        commitImgType2(data, _array)
      },
      showHistory () {
        this.$emit('openHistory', true)
      },
      businessTypeChange (_id, loadingTimeDown) {
        this.items = []
        this.actionItems = []
        this.busTimeObj = {}
        clearInterval(this.stop.stop)
        this.$nextTick(() => {
          let flow = getCache('businessFlow', _id)
          let step = getStartStep(flow)
          this.flowTemplate = Object.freeze(flow)
          this.form = {
            _id: this.detail._id,
            flow: _id,
            nextAction: '',
            nextUser: '',
            priority: this.detail.priority || '1',
            followedAgents: this.detail.followedAgents || [],
            relatedBusiness: this.detail.relatedBusiness || [],
            relatedWebchats: this.detail.relatedWebchats || [],
            relatedCallSheet: this.detail.relatedCallSheet || [],
          }
          // 定义客户字段顺序
          this.items = deepClone(step.stepFields || [])
          // 客户字段，定义内容样式
          let flowFields = flow ? flow.fields : []
          let actions = getRoleActions(step)
          this.nextAction = []
          for (let i = 0; i < actions.length; i++) {
            this.nextAction.push({label: actions[i].name, value: actions[i]._id, specific: actions[i].specific})
          }
          if (this.nextAction.length !== 0) {
            this.form.nextAction = this.nextAction[0].value
            this.nextStepChange(this.form.nextAction)
          }
          for (let i = 0; i < this.items.length; i++) {
            let row = this.items[i]
            for (let j = 0; j < row.cols.length; j++) {
              let col = row.cols[j]
              for (let k = 0; k < col.fields.length; k++) {
                let field = col.fields[k]
                let cacheField = getObjectById(flowFields, field._id)
                if (cacheField.type === 'dropdown' || cacheField.type === 'dropdownTree') {
                  let value = this.detail[cacheField._id] || ''
                  let value1 = this.detail[cacheField._id + '_1'] || ''
                  let value2 = this.detail[cacheField._id + '_2'] || ''
                  let value3 = this.detail[cacheField._id + '_3'] || ''
                  let value4 = this.detail[cacheField._id + '_4'] || ''
                  let data = [value, value1, value2, value3, value4]
                  cacheField['default'] = data
                } else if (cacheField.type === 'checkbox') {
                  cacheField['default'] = this.detail[cacheField._id] !== '' ? this.detail[cacheField._id] : [cacheField['default']]
                } else {
                  cacheField['default'] = this.detail[cacheField._id] !== '' ? this.detail[cacheField._id] : cacheField['default']
                }
                Object.assign(field, cacheField)
              }
            }
          }
          if (this.detail.master !== this.$store.state.session.user._id) {
            this.disabled = true
            this.operatePane = false
          } else {
            this.disabled = false
            this.operatePane = true
          }
          if (this.detail.saveFlag === 'temp') {
            this.tempBtn = true
          } else {
            this.tempBtn = false
          }
          if (loadingTimeDown) {
            let self = this
            busTimeDown(this.stop, this.detail, function (res) {
              // 用set方式更新，防止页面刷新
              update.call(self, self.busTimeObj, res)
            })
          }
        })
      },
      async nextStepChange (_id) {
        let flow = getCache('businessFlow', this.form.flow)
        let step = getStartStep(flow)
        let action = getFlowAction(step._id, _id)
        if (!action) {
          return
        }
        let nextStepId = action.jumpTo
        let nextStep = getCache('businessFlowStep', nextStepId) || {}
        this.nextStepName = action.name
        this.actionItems = fieldsExtend(deepClone(action.actionFields), this.flowTemplate.fields, (cacheField) => {
          if (cacheField.type === 'dropdown' || cacheField.type === 'dropdownTree') {
            let value = this.detail[cacheField._id] || ''
            let value1 = this.detail[cacheField._id + '_1'] || ''
            let value2 = this.detail[cacheField._id + '_2'] || ''
            let value3 = this.detail[cacheField._id + '_3'] || ''
            let value4 = this.detail[cacheField._id + '_4'] || ''
            return [value, value1, value2, value3, value4]
          } else if (cacheField.type === 'checkbox') {
            return this.detail[cacheField._id] !== '' ? this.detail[cacheField._id] : [cacheField['default']]
          } else {
            return this.detail[cacheField._id] !== '' ? this.detail[cacheField._id] : cacheField['default']
          }
        })
        //    工单暂存 回显暂存的 动作  start   ========================
        let stepCache = this.detail.stepCache ? this.detail.stepCache : false
        let stepCacheCur = {}    //  当前动作下的  数据
        if (stepCache) {
          for (let i = 0; i < stepCache.length; i++) {
            if (_id === stepCache[i].actionId) {
              stepCacheCur = stepCache[i]
            }
          }
        }
        this.stepCacheCurId = ''
        if (stepCacheCur.actionId) {     //   如果当前动作有暂存数据
          this.actionItemsChange = false
          this.stepCacheCurId = stepCacheCur._id
          this.$nextTick(() => {
            this.actionItems.forEach(item => {
              item.cols.forEach(one => {
                one.fields.forEach(the => {
                  if (the.type === 'dropdown' || the.type === 'dropdownTree') {
                    this.$set(the, 'default', [])
                    let well = stepCacheCur[the._id] || ''
                    let well1 = stepCacheCur[the._id + '_1'] || ''
                    let well2 = stepCacheCur[the._id + '_2'] || ''
                    let well3 = stepCacheCur[the._id + '_3'] || ''
                    let well4 = stepCacheCur[the._id + '_4'] || ''
                    this.$set(the, 'default', [well, well1, well2, well3, well4])
                  } else {
                    for (let key in stepCacheCur) {
                      if (the._id === key) {
                        this.$set(the, 'default', stepCacheCur[key])
                      }
                    }
                  }
                })
              })
            })
            this.actionItemsChange = true
          })
        }
        //    工单暂存 回显暂存的 动作  end   ========================
        if (nextStep.type !== 'sys' && action.specific) {
          // specific为true，必须指定处理人
          this.rules.nextUser[0].required = true
        } else {
          this.rules.nextUser[0].required = false
        }
        let roles = getStepRoles(nextStepId)
        let queues = getStepQueues(nextStepId)
        let queueAgents = []
        let roleAgentList = []
        let queueAgentList = []
        roleAgentList = getRoleAgents(roles, true, this.detail.createUser)
        queueAgentList = await getQueueAgents(queues, true)
        let agents = [...new Set(roleAgentList.concat(queueAgentList))]
        this.dealAgent = []
        if (agents.length !== 1) {
          this.dealAgent.push({label: this.$t('public.autoAssign'), value: ''})
        }
        for (let i = 0; i < agents.length; i++) {
          this.dealAgent.push({label: agents[i].displayName + '[' + agents[i].exten + ']', value: agents[i]._id})
        }
        if (nextStep.defaultAgent && this.dealAgent.length) {
          if (nextStep.defaultAgent === 'busCreateUser') {
            nextStep.defaultAgent = this.detail.createUser
          }
          let defaultAgent = this.dealAgent.filter((item) => {
            if (item.value === nextStep.defaultAgent) {
              return true
            }
          })
          this.form.nextUser = defaultAgent[0] ? defaultAgent[0].value : this.dealAgent[0].value
        } else {
          this.form.nextUser = this.dealAgent[0] ? this.dealAgent[0].value : ''
        }
      },
      businessTypeData () {
        let flows = getCache('businessFlow')
        let data = []
        for (var i = 0; i < flows.length; i++) {
          let flowsItem = flows[i]
          if (hasAccessForFlow(flowsItem)) {
            data.push({value: flowsItem._id, label: flowsItem.name})
          }
        }
        return data
      },
      doSaveTempBusiness (data) {
        if (this.form.flow !== this.detail.flow) {
          this.form._id = ''
        }
        this.form.customer = this.detail.customer
        this.$emit('event', {event: 'addTempBusinessTask', data: {customer: this.detail.customer, form: Object.assign(data, this.form), stepCacheCurId: this.stepCacheCurId}})
      },
      submit: throttle(function (type) {
        let data = {}
        let pass = false
        let stepFields = this.$refs.stepFields.submit(type === 'temp')
        let actionFields = this.$refs.actionFields.submit(type === 'temp')
        if (actionFields && stepFields) {
          Object.assign(data, stepFields)
          if (Object.keys(actionFields).length) {
            data.actionFields = actionFields
          }
          pass =  true
        }
        if (pass && type === 'new') {
          this.doSaveBusiness(data)
        } else if (pass && type === 'temp') {
          this.doSaveTempBusiness(data)
        } else if (!pass) { // 校验不通过
          formRollToFirstError(this.$refs.form.$el) // 表单校验有问题时，滚动到第一个el-error的位置
        }
      }, 1100, {trailing: false}),
      doSaveBusiness (data) {
        if (this.form.flow !== this.detail.flow) {
          this.form._id = ''
        }
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.form.customer = this.detail.customer
            this.$emit('event', {event: 'addBusinessTask', data: {customer: this.detail.customer, form: Object.assign(data, this.form)}})
          }
        })
      },
      closeFollowedAgents (agent) {
        this.form.followedAgents = this.form.followedAgents.filter((item) => item !== agent)
      },
      saveFollowedAgents (agents) {
        this.form.followedAgents = deepClone(agents)
      },
      popoverShow () {
        this.$refs.agentTree.setCheckedKeys()
      }
    },
    computed: {
      folllowedAgents () {
        let agents = this.form.followedAgents || []
        let agentsAll = this.$agentsMap() || {}
        return agents.map((item) => {
          let agent = agentsAll[item] || []
          return {_id: item, label: agent.displayName}
        })
      },
      totalExpireTimeDisplay () {
        if (this.busTimeObj.totalExpireTime < 0) {
          this.totalTimeColor = '#ff4949'
        } else {
          this.totalTimeColor = '#262626'
        }
        return showCountDown(this.busTimeObj.totalExpireTime || 0.1)
      },
      lastUpdateUser () {
        return getCache('agents', this.detail.lastUpdateUser).displayName
      }
    },
    beforeMount () {
      Promise.all([
        this.$store.dispatch('getCache', {type: 'options'}), this.$store.dispatch('getCache', {type: 'agents'})
      ]).then(([res1, res2]) => {
        this.businessTypeArr = this.businessTypeData()
        if (this.businessTypeArr.length === 0) {
          this.disabled = true
          this.operatePane = false
          return
        }
        let current = this.businessTypeArr.filter((item) => {
          return item.value === this.detail.flow
        })
        if (current.length === 0) {
          this.form.flow = this.businessTypeArr[0].value
          this.businessTypeChange(this.businessTypeArr[0].value)
        } else {
          this.form.flow = this.detail.flow
          this.businessTypeChange(this.detail.flow, true)
        }
      })
    },
    beforeDestroy () {
      clearInterval(this.stop.stop)
    },
    mounted () {

    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../../../assets/common.styl'
  .temporary
    position relative
    height calc(100vh - 243px)
    box-sizing border-box
    overflow-y hiden
    transform: scale(1, 1);//加入transform样式，子元素根据父元素固定定位
    .title
      padding 16px 0 10px
      font-size 14px
      font-weight bold
    .btn-wraper
      position fixed
      width 440px
      bottom 0
      padding 12px 20px 12px 0px
      box-sizing border-box
      background rgba(250,250,250,1)
      box-shadow 0px 0px 8px rgba(0,0,0,0.15)
      .btn-postion
        float right
      .btns
        text-align center
    .newbusiness-form
      height calc(100vh - 300px)
      padding 0 20px
      overflow-y auto
      overflow-x hidden
    .timedown
      float right
      padding-top 6px
      .time
        padding-right 6px
    .log
      color $cf-gray1
      margin-bottom 12px
      font-size 12px
      position relative
      line-height: 34px
      .lastUser
        padding-left 2px
        box-sizing border-box
        max-width 70px
        text-overflow ellipsis
        overflow hidden
        white-space nowrap
  .business-type
    padding 0 0 5px
  .padding-b
    padding-bottom 8px
  .width-full
    width 100%
  .line
    margin-bottom 15px
    &:before
      content ''
      height 1px
      width 100%
      display block
      border-top  1px dashed $cf-level2
  .icon-zongshichang
    color $cf-gray6
  .deal-time
    padding 0 5px
  .follow-label
    line-height 24px
    font-size 12px
  .follow-agent-wrap
    padding-left 72px
    .follow-common
      float left
      position relative
      line-height 24px
      margin 0 0 10px 10px
      padding 0 10px
      border-radius 4px
    .follow-agent-add
      cursor pointer
      border 1px solid $c-main
      color $c-main
    .follow-agent
      line-height 24px
      color #fff
      background-color $c-bus-label
      &:hover
        .el-icon-close
          display block
      .el-icon-close
        display none
        position absolute
        right -10px
        top -10px
        width 24px
        height 24px
        font-size 16px
        line-height 24px
        transform scale(0.6)
        text-align center
        color #fff
        background-color $c-pink
        border-radius 50%
        border 1px solid #fff
        cursor pointer
</style>
